﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'exercise_recording_logic.dart';
import '../../../../common/model/exercise_type.dart';

/// GPS运动记录页面
class ExerciseRecordingView extends GetView<ExerciseRecordingLogic> {
  const ExerciseRecordingView({super.key});

  @override
  Widget build(BuildContext context) {
    // 获取传递的运动类型参数
    final arguments = Get.arguments as Map<String, dynamic>?;
    final exerciseType = arguments?['exerciseType'] as ExerciseType?;
    final exerciseName = exerciseType?.name ?? 'GPS运动';

    return WillPopScope(
      onWillPop: () async {
        // 拦截返回手势，显示确认对话框
        final shouldPop = await _showExitConfirmDialog();
        if (shouldPop) {
          // 如果用户确认退出，先结束运动记录
          if (controller.state.isRecording.value) {
            // 直接设置状态来停止记录
            controller.state.isRecording.value = false;
            controller.state.isPaused.value = false;
            controller.state.isLocked.value = false;
          }
        }
        return shouldPop;
      },
      child: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          backgroundColor: Colors.orange,
          elevation: 0,
          leading: IconButton(
            icon: const Icon(Icons.close, color: Colors.white),
            onPressed: () => _showExitConfirmDialog().then((shouldPop) {
              if (shouldPop) {
                // 直接设置状态来停止记录
                if (controller.state.isRecording.value) {
                  controller.state.isRecording.value = false;
                  controller.state.isPaused.value = false;
                  controller.state.isLocked.value = false;
                }
                Get.back();
              }
            }),
          ),
          title: Text(
            exerciseName,
            style: const TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.w600,
            ),
          ),
          centerTitle: true,
        ),
        body: SafeArea(
          child: Column(
            children: [
              _buildStatusSection(),
              Expanded(
                child: _buildMapArea(),
              ),
              // 只有在运动记录状态下才显示统计数据
              Obx(() {
                if (controller.state.isRecording.value) {
                  return _buildStatsSection();
                } else {
                  return const SizedBox.shrink();
                }
              }),
              // 显示锻炼列表（仅在未开始记录时显示）
              Obx(() {
                if (!controller.state.isRecording.value) {
                  return _buildExerciseListSection();
                } else {
                  return const SizedBox.shrink();
                }
              }),
              _buildBottomControls(),
            ],
          ),
        ),
      ),
    );
  }

  /// 显示退出确认对话框
  Future<bool> _showExitConfirmDialog() async {
    final result = await Get.dialog<bool>(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Container(
          padding: EdgeInsets.all(20.w),
          decoration: BoxDecoration(
            color: Colors.grey[900],
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                '确认退出',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              SizedBox(height: 16.h),
              Text(
                '退出将结束当前运动记录，确定要退出吗？',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[300],
                ),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 20.h),
              Row(
                children: [
                  Expanded(
                    child: GestureDetector(
                      onTap: () => Get.back(result: false),
                      child: Container(
                        padding: EdgeInsets.symmetric(vertical: 12.h),
                        decoration: BoxDecoration(
                          color: Colors.grey[700],
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Center(
                          child: Text(
                            '取消',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: GestureDetector(
                      onTap: () => Get.back(result: true),
                      child: Container(
                        padding: EdgeInsets.symmetric(vertical: 12.h),
                        decoration: BoxDecoration(
                          color: Colors.red,
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Center(
                          child: Text(
                            '退出',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: false,
    );
    
    return result ?? false;
  }

  /// 构建状态栏部分
  Widget _buildStatusSection() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _buildGpsStatus(),
          _buildRingStatus(),
        ],
      ),
    );
  }

  /// 构建GPS状态
  Widget _buildGpsStatus() {
    return Obx(() {
      final gpsStrength = controller.state.gpsSignalStrength.value;
      
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              'GPS: ',
              style: TextStyle(
                color: Colors.black,
                fontSize: 12.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
            // GPS信号强度条
            ...List.generate(5, (index) {
              return Container(
                width: 3.w,
                height: 12.h,
                margin: EdgeInsets.only(right: 1.w),
                decoration: BoxDecoration(
                  color: index < gpsStrength ? Colors.black : Colors.grey[300],
                  borderRadius: BorderRadius.circular(1.r),
                ),
              );
            }),
          ],
        ),
      );
    });
  }

  /// 构建戒指连接状态
  Widget _buildRingStatus() {
    return Obx(() {
      final isConnected = controller.state.isRingConnected.value;
      
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
        decoration: BoxDecoration(
          color: isConnected ? Colors.orange : Colors.grey[600],
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.bluetooth_connected,
              color: Colors.white,
              size: 16.sp,
            ),
            SizedBox(width: 4.w),
            Text(
              isConnected ? '已连接' : '未连接',
              style: TextStyle(
                color: Colors.white,
                fontSize: 12.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      );
    });
  }

  /// 构建地图区域
  Widget _buildMapArea() {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.symmetric(horizontal: 20.w),
      decoration: BoxDecoration(
        color: Colors.grey[900],
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Stack(
        children: [
          // 地图占位区域
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.map_outlined,
                  color: Colors.grey[600],
                  size: 64.sp,
                ),
                SizedBox(height: 16.h),
                Text(
                  '正在获取GPS信号...',
                  style: TextStyle(
                    color: Colors.grey[400],
                    fontSize: 16.sp,
                  ),
                ),
                SizedBox(height: 8.h),
                Obx(() {
                  return Text(
                    'GPS信号强度: ${controller.state.gpsSignalStrength.value}/5',
                    style: TextStyle(
                      color: Colors.grey[500],
                      fontSize: 12.sp,
                    ),
                  );
                }),
              ],
            ),
          ),
          
          // 定位按钮
          Positioned(
            bottom: 20.h,
            left: 20.w,
            child: _buildLocationButton(),
          ),
        ],
      ),
    );
  }

  /// 构建定位按钮
  Widget _buildLocationButton() {
    return GestureDetector(
      onTap: () => controller.centerMapToCurrentLocation(),
      child: Container(
        width: 48.w,
        height: 48.w,
        decoration: BoxDecoration(
          color: Colors.white,
          shape: BoxShape.circle,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.3),
              spreadRadius: 1,
              blurRadius: 4,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Icon(
          Icons.my_location,
          color: Colors.orange,
          size: 24.sp,
        ),
      ),
    );
  }

  /// 构建统计数据区域
  Widget _buildStatsSection() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
      child: Column(
        children: [
          // 目标进度显示
          Obx(() {
            final targetDistance = controller.state.targetDistance.value;
            final currentDistance = controller.state.distance.value;
            final targetKm = targetDistance / 1000;
            
            return Column(
              children: [
                Text(
                  '-- -- /${targetKm.toStringAsFixed(2)}千米',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(height: 8.h),
                // 进度条
                Container(
                  height: 4.h,
                  width: double.infinity,
                  decoration: BoxDecoration(
                    color: Colors.grey[700],
                    borderRadius: BorderRadius.circular(2.r),
                  ),
                  child: Stack(
                    children: [
                      Container(
                        height: 4.h,
                        width: double.infinity,
                        decoration: BoxDecoration(
                          color: Colors.grey[700],
                          borderRadius: BorderRadius.circular(2.r),
                        ),
                      ),
                      FractionallySizedBox(
                        widthFactor: targetDistance > 0 ? (currentDistance / targetDistance).clamp(0.0, 1.0) : 0.0,
                        child: Container(
                          height: 4.h,
                          decoration: BoxDecoration(
                            color: Colors.orange,
                            borderRadius: BorderRadius.circular(2.r),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            );
          }),
          
          SizedBox(height: 16.h),
          
          // 运动数据统计
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildTimeStatItem(),
              _buildPaceStatItem(),
              _buildCaloriesStatItem(),
              _buildBpmStatItem(),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建时间统计项目
  Widget _buildTimeStatItem() {
    return Obx(() {
      final duration = controller.state.duration.value;
      final hours = duration ~/ 3600;
      final minutes = (duration % 3600) ~/ 60;
      final seconds = duration % 60;
      final timeText = '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
      
      return _buildStatColumn('时间', timeText);
    });
  }

  /// 构建配速统计项目
  Widget _buildPaceStatItem() {
    return Obx(() {
      final speed = controller.state.averageSpeed.value;
      String paceText;
      if (speed > 0) {
        final paceMinutes = (60 / speed).floor();
        final paceSeconds = ((60 / speed - paceMinutes) * 60).round();
        paceText = '${paceMinutes}\'${paceSeconds.toString().padLeft(2, '0')}\'\'';
      } else {
        paceText = '--\'--\'\'';
      }
      
      return _buildStatColumn('配速', paceText);
    });
  }

  /// 构建卡路里统计项目
  Widget _buildCaloriesStatItem() {
    return Obx(() {
      final calories = controller.state.calories.value;
      return _buildStatColumn('千卡', calories.toString());
    });
  }

  /// 构建心率统计项目
  Widget _buildBpmStatItem() {
    return _buildStatColumn('BPM', '--');
  }

  /// 构建统计项目列
  Widget _buildStatColumn(String label, String value) {
    return Column(
      children: [
        Text(
          value,
          style: TextStyle(
            color: Colors.white,
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          label,
          style: TextStyle(
            color: Colors.grey[400],
            fontSize: 12.sp,
          ),
        ),
      ],
    );
  }

  /// 构建底部控制区域
  Widget _buildBottomControls() {
    return Container(
      padding: EdgeInsets.all(20.w),
      child: Obx(() {
        final isRecording = controller.state.isRecording.value;
        
        if (isRecording) {
          // 运动中状态：显示锁定/结束 和 暂停/继续按钮
          return Row(
            children: [
              Expanded(child: _buildLockButton()),
              SizedBox(width: 16.w),
              Expanded(child: _buildPauseButton()),
            ],
          );
        } else {
          // 未开始状态：显示目标设置和开始按钮
          return Row(
            children: [
              Expanded(child: _buildGoalButton()),
              SizedBox(width: 16.w),
              Expanded(child: _buildStartButton()),
            ],
          );
        }
      }),
    );
  }

  /// 构建目标设置按钮
  Widget _buildGoalButton() {
    return GestureDetector(
      onTap: () => controller.showGoalSettings(),
      child: Container(
        height: 48.h,
        decoration: BoxDecoration(
          color: Colors.transparent,
          borderRadius: BorderRadius.circular(24.r),
          border: Border.all(color: Colors.white, width: 1),
        ),
        child: Center(
          child: Text(
            '目标设置',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16.sp,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ),
    );
  }

  /// 构建开始按钮
  Widget _buildStartButton() {
    return Obx(() {
      final canStart = controller.state.gpsSignalStrength.value >= 3; // 需要至少3格信号
      
      return GestureDetector(
        onTap: canStart ? () => controller.startRecording() : null,
        child: Container(
          height: 48.h,
          decoration: BoxDecoration(
            color: canStart ? Colors.orange : Colors.grey[600],
            borderRadius: BorderRadius.circular(24.r),
          ),
          child: Center(
            child: Text(
              '开始',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
      );
    });
  }

  /// 构建锁定/结束按钮
  Widget _buildLockButton() {
    return Obx(() {
      final isLocked = controller.state.isLocked.value;
      
      return GestureDetector(
        onTap: () => controller.toggleLock(),
        child: Container(
          height: 48.h,
          decoration: BoxDecoration(
            color: Colors.transparent,
            borderRadius: BorderRadius.circular(24.r),
            border: Border.all(color: Colors.white, width: 1),
          ),
          child: Center(
            child: Text(
              isLocked ? '结束' : '锁定',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ),
      );
    });
  }

  /// 构建暂停/继续按钮
  Widget _buildPauseButton() {
    return Obx(() {
      final isPaused = controller.state.isPaused.value;
      
      return GestureDetector(
        onTap: () => controller.togglePause(),
        child: Container(
          height: 48.h,
          decoration: BoxDecoration(
            color: isPaused ? Colors.orange : Colors.red,
            borderRadius: BorderRadius.circular(24.r),
          ),
          child: Center(
            child: Text(
              isPaused ? '继续' : '暂停',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
      );
    });
  }
  
  /// 构建锻炼列表区域
  Widget _buildExerciseListSection() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '今日锻炼记录',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
              Obx(() {
                if (controller.isLoadingExerciseList.value) {
                  return SizedBox(
                    width: 16.w,
                    height: 16.w,
                    child: const CircularProgressIndicator(
                      strokeWidth: 2,
                      color: Colors.orange,
                    ),
                  );
                }
                return GestureDetector(
                  onTap: () => controller.loadExerciseList(),
                  child: Icon(
                    Icons.refresh,
                    color: Colors.orange,
                    size: 20.sp,
                  ),
                );
              }),
            ],
          ),
          SizedBox(height: 8.h),
          Obx(() {
            if (controller.exerciseList.isEmpty) {
              return Container(
                padding: EdgeInsets.symmetric(vertical: 16.h),
                child: Center(
                  child: Text(
                    '暂无锻炼记录',
                    style: TextStyle(
                      color: Colors.grey[400],
                      fontSize: 14.sp,
                    ),
                  ),
                ),
              );
            }
            
            return Container(
              constraints: BoxConstraints(maxHeight: 150.h),
              child: ListView.builder(
                shrinkWrap: true,
                itemCount: controller.exerciseList.length,
                itemBuilder: (context, index) {
                  final exercise = controller.exerciseList[index];
                  return _buildExerciseListItem(exercise);
                },
              ),
            );
          }),
        ],
      ),
    );
  }
  
  /// 构建锻炼列表项
  Widget _buildExerciseListItem(Map<String, dynamic> exercise) {
    // 从rawData中解析数据（SDK返回的是toString格式）
    final rawData = exercise['rawData']?.toString() ?? '';
    
    return GestureDetector(
      onTap: () => controller.viewExerciseDetail(exercise),
      child: Container(
        margin: EdgeInsets.only(bottom: 8.h),
        padding: EdgeInsets.all(12.w),
        decoration: BoxDecoration(
          color: Colors.grey[800],
          borderRadius: BorderRadius.circular(8.r),
        ),
        child: Row(
          children: [
            // 运动图标
            Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: Colors.orange.withValues(alpha: 0.2),
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Icon(
                Icons.directions_run,
                color: Colors.orange,
                size: 20.sp,
              ),
            ),
            SizedBox(width: 12.w),
            // 运动信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '训练记录',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    rawData.length > 50 ? '${rawData.substring(0, 50)}...' : rawData,
                    style: TextStyle(
                      color: Colors.grey[400],
                      fontSize: 12.sp,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
            // 箭头
            Icon(
              Icons.arrow_forward_ios,
              color: Colors.grey[500],
              size: 16.sp,
            ),
          ],
        ),
      ),
    );
  }
}
